package com.heima.admin.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.admin.mapper.AdSensitiveMapper;
import com.heima.admin.service.AdChannelService;
import com.heima.admin.service.WemediaNewsAutoScanService;
import com.heima.aliyun.GreenImageScan;
import com.heima.aliyun.GreenTextScan;
import com.heima.common.exception.CustomException;
import com.heima.feigns.article.ArticleFeign;
import com.heima.feigns.wemedia.WemediaFeign;
import com.heima.model.admin.pojos.AdChannel;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.SensitiveWordUtil;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 *
 */
@Service
@Slf4j
public class WemediaNewsAutoScanServiceImpl implements WemediaNewsAutoScanService {
    @Autowired
    WemediaFeign wemediaFeign;

    @Value("${file.oss.web-site}")
    private String webSite;

    @Resource
    AdSensitiveMapper adSensitiveMapper;

    @Autowired
    GreenTextScan greenTextScan;

    @Autowired
    GreenImageScan greenImageScan;
    @Override
//    @GlobalTransactional
    public void autoScanByMediaNewsId(Integer wmNewsId) {
        // 检查参数
        if (wmNewsId == null){
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        // 根据自媒体新闻id查询文章
        WmNews wmNews = wemediaFeign.findById(wmNewsId);
        if (wmNews == null){
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST,"查询的文章信息不存在");
        }
        // 判断文章的状态，如果是4或者8就可以将数据同步到文章表
        /*if (wmNews.getStatus() == 4 || wmNews.getStatus() == 8){
            // 自定义同步方法
            pulishArticle(wmNews);
        }*/
        // 还要考虑时间
        if (wmNews.getStatus().equals(WmNews.Status.ADMIN_SUCCESS.getCode()) && wmNews.getPublishTime().getTime() <= System.currentTimeMillis()){
            // 发布文章
            publishArticle(wmNews);
            return;
        }
        if (wmNews.getStatus().equals(WmNews.Status.SUCCESS.getCode()) && wmNews.getPublishTime().getTime() <= System.currentTimeMillis()){
            publishArticle(wmNews);
            return;
        }
        // 草稿不用管
        if (wmNews.getStatus().equals(WmNews.Status.NORMAL.getCode())){
            return;
        }
        // 待审核需要进行审核
        if (wmNews.getStatus().equals(WmNews.Status.SUBMIT.getCode())) {
            // 进行审核，调用自定义审核方法
            // 抽取wmNews中的内容和图片
            Map<String,Object> contentAndImagesResult = handleTextAndImages(wmNews);
            // 通过敏感词审核
            // 先获取敏感词列表
            List<String> allSensitive = adSensitiveMapper.findAllSensitive();
            // 调用敏感词审核工具类
            SensitiveWordUtil.initMap(allSensitive);
            Map<String, Integer> isSensitiveScan = SensitiveWordUtil.matchWords(contentAndImagesResult.get("text").toString());
            if (isSensitiveScan.size() > 0){
                // 包含敏感词,审核失败
                // 更新wmNews信息
                wmNews.setStatus((short)2);
                wmNews.setReason("文章中包含了敏感词"+isSensitiveScan);
                wemediaFeign.updateWmNews(wmNews);
                System.out.println("包含敏感词:(测试用)"+isSensitiveScan);
                return;
            }
            // 通过阿里云审核内容
            Boolean isTextScan = handleTextScan(contentAndImagesResult.get("text").toString(),wmNews);
            if (isTextScan == false){
                return;
            }
            // 通过阿里云审核图片
            Boolean isImageScan = handleImagesScan((List)contentAndImagesResult.get("image"),wmNews);
            if (isImageScan == false){
                return;
            }
            // 判断时间
            if (wmNews.getPublishTime().getTime() >= System.currentTimeMillis()){
                // 没到发布时间，待发布状态
                wmNews.setStatus(WmNews.Status.SUCCESS.getCode());
                wemediaFeign.updateWmNews(wmNews);
            }
            // 发布文章
            publishArticle(wmNews);
        }

    }

    private Boolean handleImagesScan(List<String> image, WmNews wmNews) {
        // 没有图则不需要进行审核
        if (image == null){
            return true;
        }
        boolean flag = true;
        // 对列表进行去重
        List<String> images = image.stream()
                .distinct()
                .collect(Collectors.toList());
        try {
            Map map = greenImageScan.imageUrlScan(images);
            if (map.get("suggestion").equals("block")){
                wmNews.setStatus(WmNews.Status.FAIL.getCode());
                wmNews.setReason("图片内容违规");
                wemediaFeign.updateWmNews(wmNews);
                flag = false;
            }
            if (map.get("suggestion").equals("review")){
                wmNews.setStatus(WmNews.Status.ADMIN_AUTH.getCode());
                wmNews.setReason("图片内容有异，须等待人工审核");
                wemediaFeign.updateWmNews(wmNews);
                flag = false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }


    // 阿里云审核文章内容
    private Boolean handleTextScan(String text, WmNews wmNews) {
        boolean flag = true;
        try {
            Map map = greenTextScan.greenTextScan(text);
            // 审核不通过
            if (map.get("suggestion").equals("block")){
                wmNews.setStatus(WmNews.Status.FAIL.getCode());
                wmNews.setReason("文章包含敏感词");
                wemediaFeign.updateWmNews(wmNews);
                flag = false;
            }
            if (map.get("suggestion").equals("review")){
                wmNews.setStatus(WmNews.Status.ADMIN_AUTH.getCode());
                wmNews.setReason("需要进行人工审核");
                wemediaFeign.updateWmNews(wmNews);
                flag = false;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    private Map<String, Object> handleTextAndImages(WmNews wmNews) {
        // 抽取文章
        String content = wmNews.getContent();
        // 转换成json格式
        List<Map> contentMap = JSON.parseArray(content, Map.class);
        // 其中type类型为image的是图片，类型为text的是文章
        // 将文章拿出来拼接成一个字符串
        String contentText = contentMap.stream()
                .filter(map -> map.get("type").equals("text"))
                .map(value -> value.get("value").toString())
                .collect(Collectors.joining("_hmtt_"));
        // 将标题中的内容拿出来和内容拼接起来
        String title = wmNews.getTitle();
        contentText = title+contentText;
        // 抽取图片信息
        List<String> contentImage = contentMap.stream()
                .filter(map -> map.get("type").equals("image"))
                .map(value -> value.get("value").toString())
                .collect(Collectors.toList());
        // 将封面也封装进去
        String images = wmNews.getImages();
        if (StringUtils.isNotBlank(images)){
            contentImage.addAll(
                    Stream.of(images.split(","))
                            .map(x -> webSite+x)
                            .collect(Collectors.toList())
            );
        }

        // 封装结果
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("text",contentText);
        resultMap.put("image",contentImage);

        return resultMap;
    }

    // 将wmNews表中的信息同步到文章表中
    private void publishArticle(WmNews wmNews) {
        //保存app相关文章
        ResponseResult responseResult = saveArticle(wmNews);
        if(!responseResult.getCode().equals(0)){
            throw new RuntimeException("文章审核保存app文章失败");
        }
        Object data = responseResult.getData();
        //修改自媒体文章状态，状态为9  审核通过
        wmNews.setArticleId((Long) data);
        wmNews.setStatus((short)9);
        wmNews.setReason("审核通过");
        wemediaFeign.updateWmNews(wmNews);
    }

    /**
     * 保存文章到app
     * @param wmNews
     * @return
     */
    @Autowired
    AdChannelService adChannelService;
    @Autowired
    ArticleFeign articleFeign;

    private ResponseResult saveArticle(WmNews wmNews) {
        ArticleDto articleDto = new ArticleDto();
        BeanUtils.copyProperties(wmNews,articleDto);
        articleDto.setId(null);
        if (wmNews.getId() != null){
            articleDto.setId(wmNews.getArticleId());
        }
        // 布局
        articleDto.setLayout(wmNews.getType());
        articleDto.setFlag((byte)0);
        // 频道
        if (wmNews.getChannelId() != null){
            articleDto.setChannelId(wmNews.getChannelId());
            AdChannel adChannel = adChannelService.getById(wmNews.getId());
            if (adChannel != null){
                articleDto.setChannelName(adChannel.getName());
            }
        }
        // 设置作者信息
        WmUser wmUser = wemediaFeign.findWmUserById(wmNews.getUserId());
        if (wmUser == null || wmUser.getStatus().intValue() != 9) { // 非法用户
            throw new CustomException(AppHttpCodeEnum.ILLEGAL_USER);
        }
        if (StringUtils.isNotBlank(wmUser.getName())){
            articleDto.setAuthorName(wmUser.getName());
        }
        // 文章内容
        articleDto.setContent(wmNews.getContent());
        // 保存信息
        return articleFeign.saveArticle(articleDto);
    }
}
